package com.heba.greenmulu.diary;

import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.SpannedString;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.heba.Cfg;
import com.heba.Debug;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.ItemShareObject;
import com.heba.bean.ShareObject;
import com.heba.bean.diary.ItemDiaryCommentObject;
import com.heba.bean.diary.ItemDiaryCommentReplyObject;
import com.heba.bean.diary.ItemDiaryDetailObject;
import com.heba.bean.diary.ItemDiaryImageObject;
import com.heba.bean.diary.ItemDiaryTagObject;
import com.heba.bean.diary.ItemUserInfoObject;
import com.heba.bean.product.ItemProductInfoObject;
import com.heba.config.CommonConfig;
import com.heba.dialog.CustomDialogView;
import com.heba.event.MessageEvent;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.ItemReportActivity;
import com.heba.greenmulu.R;
import com.heba.greenmulu.businesslist.BusinessHomePageActivity;
import com.heba.greenmulu.businesslist.BusinessPersonActivity;
import com.heba.greenmulu.hashtag.ItemHashTagPageActivity;
import com.heba.greenmulu.message.ItemMessageSendActivity;
import com.heba.greenmulu.scan.ItemProductDetailActivity;
import com.heba.helper.DateHelper;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.loader.GlideImageLoader;
import com.heba.popupwindow.DiaryCommentPopupWindow;
import com.heba.popupwindow.SharePopupWindow;
import com.heba.popupwindow.callback.ShareListener;
import com.heba.utils.CommonUtils;
import com.heba.utils.DensityUtils;
import com.heba.utils.GlideUtil;
import com.heba.utils.ToastShow;
import com.heba.view.FlowLayout;
import com.heba.view.MyRatingBarView;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

/**
 * 日记详情页面
 * Created by jason on 2020/2/8.
 */
public class ItemDiaryDetailActivity extends BaseActivity {

    private View view_background;
    private View topbar;
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private QuickAdapter recycleAdapter;

    private View view_bar;   //底部評論 點讚 傳送 View

    /**
     * 分享彈出框
     */
    private SharePopupWindow sharePopupWindow;
    private ShareObject shareObject;

    /**
     * 評論彈出框
     */
    private DiaryCommentPopupWindow commentPopupWindow;

    private ItemDiaryDetailObject detailObject;
    private List<ItemDiaryCommentObject> commentObjectList;

    private String diaryID;
    private int type = 0;  //判斷是評論還是回復  0表示留言 1表示回復
    private String toUserID;  //留言的目標用戶ID
    private String feedbackID;  //type = 1時必填

    private boolean isTopViewTransparent = true;  //topview颜色是否透明

    private int iResult = 0;  //计算滑动距离

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary_detail);
        /**
         * 设置透明状态栏  不设置颜色默认透明状态栏
         */
        ImmersionBar.with(this)
                .statusBarView(R.id.top_view)
                .init();
        initTopbar();
        findViewById();
        initView();
        initPopupWindow();
        getDiaryDetailData();
    }

    @Override
    protected void findViewById() {
        view_background = findViewById(R.id.view_background);
        topbar = findViewById(R.id.topbar);
        refreshLayout = findViewById(R.id.refreshLayout);
        recyclerView = findViewById(R.id.recyclerView);
        view_bar = findViewById(R.id.view_bar);
    }

    @Override
    protected void initView() {
        txt_title.setVisibility(View.INVISIBLE);
        txt_title.setText(getResources().getString(R.string.diary_diary_detail));
        shareObject = new ShareObject();

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            diaryID = bundle.getString(CommonConfig.DIARY_ID, "");
        }

        detailObject = new ItemDiaryDetailObject();
        commentObjectList = new ArrayList<>();

        recycleAdapter = new QuickAdapter<ItemDiaryCommentObject>(commentObjectList) {
            @Override
            public int getLayoutId(int viewType) {
                switch (viewType) {
                    case 0:
                        return R.layout.recycle_item_diary_detail_header;
                    default:
                        return R.layout.recycle_item_diary_comment_row;
                }
            }

            @Override
            public void convert(VH holder, ItemDiaryCommentObject data, int position) {
                if (position == 0) {
                    /**
                     * 显示头部数据
                     */
                    if (detailObject != null) {
                        /**
                         * 图片轮播
                         */
                        Banner banner = holder.getView(R.id.viewPager);
                        ImageView iv_play = holder.getView(R.id.iv_play);

                        iv_play.setVisibility(View.GONE);
                        if (!detailObject.getImageList().isEmpty()) {
                            List<ItemDiaryImageObject> imageObjects = detailObject.getImageList();
                            banner.setImages(imageObjects)
                                    .setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                                    .setImageLoader(new GlideImageLoader())
                                    .isAutoPlay(true)
                                    .setDelayTime(5000)
                                    .start();

                            //显示视频
                            if (imageObjects.size() == 1 && imageObjects.get(0).getType() == 1) {
                                iv_play.setVisibility(View.VISIBLE);
                            }
                        }

                        /**
                         * 輪播圖片點擊事件
                         */
                        banner.setOnBannerListener(new OnBannerListener() {
                            @Override
                            public void OnBannerClick(int position) {
                                if (!detailObject.getImageList().isEmpty()) {
                                    //跳转视频播放页面
                                    ItemDiaryImageObject object = detailObject.getImageList().get(0);
                                    if (object.getType() == 1 && object.getVideoUrl() != null) {
                                        Bundle bundle = new Bundle();
                                        bundle.putInt(CommonConfig.TYPE, 1);
                                        bundle.putString(CommonConfig.DIARY_IMAGE, object.getImageUrl());
                                        bundle.putString(CommonConfig.DIARY_VIDEO, object.getVideoUrl());
                                        openActivity(VideoPlayNetworkActivity.class, bundle);
                                    } else {
                                        //跳转图片大图显示页面
//                                        List<ItemDiaryImageObject> diaryImageObjects = detailObject.getImageList();
//                                        Bundle bundle = new Bundle();
//                                        bundle.putSerializable(CommonConfig.DIARY_IMAGE_LIST, (Serializable) diaryImageObjects);
//                                        bundle.putInt(CommonConfig.POSITION, position);
//                                        openActivityWithFadeInAnimation(ItemDiaryImageShowActivity.class, bundle);
                                    }
                                }
                            }
                        });

                        /**
                         * 显示日记数据
                         */
//                        String diaryText = detailObject.getContent();
//                        SpannableString string = new SpannableString(diaryText);
//                        for (int i = 0;i<detailObject.getUserList().size();i++){
//                            ItemUserInfoObject tempObj = detailObject.getUserList().get(i);
//                            string = CommonUtils.matcherSearchText(getBaseContext(),diaryText,tempObj.getAccount());
//                        }
//                        TextView textView = holder.getView(R.id.tv_desc);
//                        textView.setText(string);
//                        holder.setText(R.id.tv_desc, CommonUtils.getDecodeText(detailObject.getContent()));
                        StringBuffer buffer = new StringBuffer();
                        String diaryText = CommonUtils.getDecodeText(detailObject.getContent());
                        buffer.append(diaryText);

                        SpannableStringBuilder ssb = new SpannableStringBuilder();

                        if (detailObject.getUserList() != null){
                            for (int i = 0;i < detailObject.getUserList().size();i++){
                                ItemUserInfoObject obj = detailObject.getUserList().get(i);
                                buffer.replace(buffer.indexOf(obj.getAccount()),buffer.indexOf(obj.getAccount())+obj.getAccount().length(),"<font color=\"#95CF63\">"+obj.getAccount()+"</font>");

                            }
                        }
//        if (this.getUserList() != null){
//            for(int i = 0;i<this.getUserList().size();i++){
//                ItemUserInfoObject obj = this.getUserList().get(i);
//                diaryText = diaryText.replaceAll("@"+obj.getAccount(),"<font color=\"#333333\">@</font>"+"<font color=\"#95CF63\">"+obj.getAccount()+"</font>");
//            }
//        }
                        if (detailObject.getTalkList() != null){
                            for (int i = 0 ; i <detailObject.getTalkList().size();i++){
                                ItemDiaryTagObject obj = detailObject.getTalkList().get(i);
                                int index = buffer.indexOf(obj.getContent());
                                if (index != -1){
                                    buffer.replace(buffer.indexOf(obj.getContent())+1,buffer.indexOf(obj.getContent())+1+obj.getContent().length(),"<font color=\"#95CF63\">"+obj.getContent().split("#")[1]+"</font>");

                                }
                            }
                        }
                        diaryText = buffer.toString();
                        ssb.append(Html.fromHtml(diaryText));
                        String htmlString =  Html.fromHtml(diaryText).toString();
                        TextView textView = holder.getView(R.id.tv_desc);
                        if (detailObject.getUserList() != null){
                            for (int i = 0;i < detailObject.getUserList().size();i++){
                                ItemUserInfoObject obj = detailObject.getUserList().get(i);

                                ssb.setSpan(new ClickableSpan() {
                                    @Override
                                    public void onClick(@NonNull View widget) {
                                        Bundle bundle = new Bundle();
                                        bundle.putString(CommonConfig.SEND_USER_ID, obj.getUserID());
                                        if (obj.getAccountType().equals("0") ){

                                            openActivity(ItemPersonHomePageActivity.class, bundle);
                                        }else{
                                            openActivity(BusinessPersonActivity.class, bundle);
                                        }
                                    }
                                    @Override
                                    public void updateDrawState(TextPaint ds) {
                                        ds.setUnderlineText(false);
                                    }
                                },htmlString.indexOf("@"+obj.getAccount().charAt(0))+1,htmlString.indexOf(obj.getAccount().charAt(0))+obj.getAccount().length(),0);
                            }
                        }

                        if (detailObject.getTalkList() != null){
                            for (int i = 0 ; i <detailObject.getTalkList().size();i++){
                                ItemDiaryTagObject obj = detailObject.getTalkList().get(i);
                                int index = htmlString.indexOf(obj.getContent());
                                if (index != -1){


                                    ssb.setSpan(new ClickableSpan() {
                                        @Override
                                        public void onClick(@NonNull View widget) {
                                            Bundle bundle = new Bundle();
                                            bundle.putString(CommonConfig.HASHTAG_ID, obj.getHashtagID());
                                            openActivity(ItemHashTagPageActivity.class, bundle);

                                        }
                                        @Override
                                        public void updateDrawState(TextPaint ds) {
                                            ds.setUnderlineText(false);
                                        }
                                    },htmlString.indexOf(obj.getContent().charAt(0)),htmlString.indexOf(obj.getContent().charAt(0))+obj.getContent().length(),0);

                                }
                            }
                        }
                        textView.setHighlightColor(ContextCompat.getColor(getBaseContext(),R.color.transparent));
                        textView.setMovementMethod(LinkMovementMethod.getInstance());//加上这句话才有效果
                        textView.setText(ssb,TextView.BufferType.SPANNABLE);

                        holder.setText(R.id.tv_read_num, String.format(getResources().getString(R.string.scan_product_comment_views), detailObject.getViews()));

                        /**
                         * 显示产品信息
                         */
                        View view_product = holder.getView(R.id.view_product);
                        view_product.setVisibility(View.GONE);
                        if (!detailObject.getProduct().isEmpty()) {
                            view_product.setVisibility(View.VISIBLE);
                            ItemProductInfoObject infoObject = detailObject.getProduct().get(0);
                            GlideUtil.loadImageWithDefaultPlaceHolder(ItemDiaryDetailActivity.this, infoObject.getIcon(), holder.getView(R.id.iv_product));
                            holder.setText(R.id.tv_product, infoObject.getBrandName());
                            holder.setText(R.id.tv_content, infoObject.getProductName());
                            holder.setText(R.id.tv_weight, String.format(getResources().getString(R.string.per_serving_size), infoObject.
                                    getPackageSize(), infoObject.getPackageUnit(), CommonUtils.subZeroAndDot(infoObject.getServingSize()), infoObject.getServingSizeUnit()));
                            MyRatingBarView rb_view = holder.getView(R.id.rb_view);
                            rb_view.setStar(detailObject.getStar());

                            view_product.setOnClickListener(v -> {
                                Bundle bundle1 = new Bundle();
                                bundle1.putString(CommonConfig.PRODUCT_ID, infoObject.getProductID());
                                openActivity(ItemProductDetailActivity.class, bundle1);
                            });
                        }

                        /**
                         * 添加话题标签
                         */
//                        FlowLayout fl_tag_view = holder.getView(R.id.fl_tag_view);
//                        updateFlowView(fl_tag_view, detailObject.getTalkList());
                    }
                } else {
                    /**
                     * 显示评论数据
                     */
                    ImageView iv_avatar = holder.getView(R.id.iv_avatar);
                    GlideUtil.loadImageWithPlaceHolderID(ItemDiaryDetailActivity.this, data.getIcon(), iv_avatar, R.drawable.icon_head_portrait);
                    holder.setText(R.id.tv_name, data.getNickname());
                    holder.setText(R.id.tv_time, DateHelper.transferDateString(ItemDiaryDetailActivity.this, data.getTimeCreated()));
                    holder.setText(R.id.tv_comment, CommonUtils.getDecodeText(data.getMessage()));

                    /**
                     * 跳转用户主页
                     */
                    iv_avatar.setOnClickListener(v -> {
                        Bundle bundle1 = new Bundle();
                        bundle1.putString(CommonConfig.SEND_USER_ID, data.getUserID());
                        if (data.getAccountType() == 0){
                            openActivity(ItemPersonHomePageActivity.class, bundle);
                        }else{
                            openActivity(BusinessPersonActivity.class, bundle);
                        }
                    });

                    /**
                     * 回复用户留言
                     */
                    holder.itemView.setOnClickListener(v -> {
                        //判斷不能回復自己的留言
                        if (data.getUserID().equals(Cfg.UserID)) {
                            ToastShow.displayToast(ItemDiaryDetailActivity.this, getResources().getString(R.string.diary_comment_tips));
                            return;
                        }
                        type = 1;
                        feedbackID = data.getFeedbackID();
                        toUserID = data.getUserID();
                        showCommentPopupView(v, type, feedbackID, toUserID,
                                String.format(getResources().getString(R.string.diary_reply_hint), data.getNickname()));
                    });

                    /**
                     * 显示评论回复数据
                     */
                    LinearLayout ll_reply_view = holder.getView(R.id.ll_reply_view);
                    ll_reply_view.setVisibility(View.GONE);
                    if (!data.getReplyList().isEmpty()) {
                        ll_reply_view.setVisibility(View.VISIBLE);
                        updateCommentReplyView(ll_reply_view, data.getReplyList(), data.getFeedbackID());
                    }
                }
            }

            @Override
            public int getItemViewType(int position) {
                switch (position) {
                    case 0:
                        return 0;
                    default:
                        return 1;
                }
            }
        };

        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(false);

        /**
         * 分享彈出框
         */
        img_right.setOnClickListener(v -> {
            if (null == detailObject)
                return;
            view_background.setVisibility(View.VISIBLE);
            shareObject.setShareTitle(String.format(this.getResources().getString(R.string.share_diary_title), detailObject.getNickname()));
            shareObject.setShareContent(detailObject.getContent());
            if (detailObject.getImageList() != null && !detailObject.getImageList().isEmpty())
                shareObject.setShareImageUrl(detailObject.getImageList().get(0).getImageUrl());
            shareObject.setShareLink(detailObject.getLink());
            sharePopupWindow.setShareObject(shareObject);
            if (Cfg.UserID.equals(detailObject.getUserID())) {
                sharePopupWindow.setShareList(updateShareList1(), updateShareList2(true));
            } else {
                sharePopupWindow.setShareList(updateShareList1(), updateShareList2(false));
            }
            sharePopupWindow.showAtLocation(img_right, Gravity.BOTTOM, 0, 0);
        });

        /**
         * recyclerview滑动监听
         */
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //找到即将移出屏幕Item的position,position是移出屏幕item的数量
                int position = layoutManager.findFirstVisibleItemPosition();

                if (position > 0)
                    return;

                //根据position找到这个Item
                View firstVisiableChildView = layoutManager.findViewByPosition(position);
                //获取Item的高
                int itemHeight = firstVisiableChildView.getHeight();
                //算出该Item还未移出屏幕的高度
                int itemTop = firstVisiableChildView.getTop();
                //position移出屏幕的数量*高度得出移动的距离
                int iposition = position * itemHeight;
                //减去该Item还未移出屏幕的部分可得出滑动的距离
                iResult = iposition - itemTop;
                Debug.Log(TAG, "recyclerView 滑动距离 " + iResult);

                Debug.Log(TAG, "recyclerView 滑动距离 computeVerticalScrollOffset =  " + recyclerView.computeVerticalScrollOffset());
                /**
                 * 根据计算的距离动态改变状态栏颜色
                 */
                int scrollDistance = DensityUtils.dip2px(ItemDiaryDetailActivity.this, 50);
                if (iResult >= scrollDistance && isTopViewTransparent) {
                    isTopViewTransparent = false;
                    txt_title.setVisibility(View.VISIBLE);
                    ImmersionBar.with(ItemDiaryDetailActivity.this)
                            .statusBarColorTransform(R.color.colorGreen)
                            .addViewSupportTransformColor(topbar)
                            .barAlpha(1.0f)
                            .init();
                } else if (iResult < scrollDistance && !isTopViewTransparent) {
                    isTopViewTransparent = true;
                    txt_title.setVisibility(View.INVISIBLE);
                    ImmersionBar.with(ItemDiaryDetailActivity.this)
                            .statusBarColorTransform(R.color.colorGreen)
                            .addViewSupportTransformColor(topbar)
                            .barAlpha(0.0f)
                            .init();
                }
            }
        });
    }

    /**
     * 分享彈出框
     */
    private void initPopupWindow() {
        sharePopupWindow = new SharePopupWindow(this, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        sharePopupWindow.setShareList(updateShareList1(), updateShareList2(false));


        /**
         * 分享接口實現
         */
        sharePopupWindow.setOnShareListener(new ShareListener(ItemDiaryDetailActivity.this) {
            @Override
            public void collectDiary() {
                /**
                 * 收藏日記貼
                 */
                if (detailObject.getIsCollected() == 1) {
                    ToastShow.displayToast(ItemDiaryDetailActivity.this, getResources().getString(R.string.diary_has_been_collect));
                    return;
                }
                new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                    @Override
                    public void Success() {
                        ToastShow.displayToast(ItemDiaryDetailActivity.this, getResources().getString(R.string.diary_collect_success));
                    }

                    @Override
                    public void Fail(String error) {

                    }
                }).collectDiary(ItemDiaryDetailActivity.this, diaryID);
            }

            @Override
            public void reportDiary() {
                Bundle bundle = new Bundle();
                bundle.putInt(CommonConfig.TYPE, 2);
                bundle.putString(CommonConfig.REPORT_ID, diaryID);
                openActivity(ItemReportActivity.class, bundle);
            }

            @Override
            public void deleteDiary() {
                /**
                 * 删除日记
                 */
                new CustomDialogView(new CustomDialogView.OnCustomDialogClickListener() {
                    @Override
                    public void onYesClick() {
                        progressDialog.show();
                        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                            @Override
                            public void Success() {
                                progressDialog.dismiss();
                                ToastShow.displayToast(ItemDiaryDetailActivity.this, getResources().getString(R.string.diary_delete_success));
                                //通知刷新
                                MessageEvent event = new MessageEvent();
                                event.setEvent(CommonConfig.EVENT_REFRESH_DIARY_LIST);
                                EventBus.getDefault().post(event);
                                finishActivity();
                            }

                            @Override
                            public void Fail(String error) {
                                progressDialog.dismiss();
                            }
                        }).deleteDiary(ItemDiaryDetailActivity.this, diaryID);
                    }

                    @Override
                    public void onNoClick() {

                    }
                }).showDialog(ItemDiaryDetailActivity.this, getResources().getString(R.string.diary_delete_tips), "");
            }
        });

        sharePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                view_background.setVisibility(View.GONE);
            }
        });

        sharePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                view_background.setVisibility(View.GONE);
            }
        });

        /**
         * 評論彈出框
         */
        commentPopupWindow = new DiaryCommentPopupWindow(this, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        commentPopupWindow.setOnDiaryCommentListener(content -> {
            /**
             * 用户留言处理
             */
            progressDialog.show();
            new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                @Override
                public void Success() {
                    /**
                     * 留言评论成功，更新数据
                     */
                    progressDialog.dismiss();
                    commentPopupWindow.setCommentHint(getResources().getString(R.string.diary_comment));
                    commentPopupWindow.setCommentText("");
                    //刷新日記列表數據
                    EventBus.getDefault().post(new MessageEvent(CommonConfig.EVENT_REFRESH_DIARY_LIST));
                    getDiaryDetailData();
                }

                @Override
                public void Fail(String error) {
                    progressDialog.dismiss();
                }
            }).addFeedback(ItemDiaryDetailActivity.this, diaryID, type, content, toUserID, feedbackID);
        });
        commentPopupWindow.setOnDismissListener(() -> view_background.setVisibility(View.GONE));
    }

    /**
     * 分享至社交軟件
     */
    private List<ItemShareObject> updateShareList1() {
        List<ItemShareObject> shareList = new ArrayList<>();
        int[] ids = {R.drawable.icon_more_share_facebook, R.drawable.icon_more_share_whatsapp, R.drawable.icon_more_share_wechat, R.drawable.icon_more_share_friends};
        String[] contents = getResources().getStringArray(R.array.share_contents_normal);
        int[] shareTypes = {CommonConfig.SHARE_TO_FACEBOOK, CommonConfig.SHARE_TO_WHATSAPP, CommonConfig.SHARE_TO_WECHAT, CommonConfig.SHARE_TO_CIRCLE};
        for (int i = 0; i < ids.length; i++) {
            ItemShareObject shareObject = new ItemShareObject();
            shareObject.setImageID(ids[i]);
            shareObject.setShareContent(contents[i]);
            shareObject.setShareType(shareTypes[i]);
            shareList.add(shareObject);
        }
        return shareList;
    }

    /**
     * 本地分享
     *
     * @param withDiaryDelete 是否包含删除日记
     * @return
     */
    private List<ItemShareObject> updateShareList2(boolean withDiaryDelete) {
        List<ItemShareObject> shareList = new ArrayList<>();
        int[] ids1 = {R.drawable.icon_more_collection, R.drawable.icon_more_report, R.drawable.icon_more_delete};
        String[] contents1 = getResources().getStringArray(R.array.share_contents_diary);
        int[] shareTypes1 = {CommonConfig.SHARE_TO_COLLECT_DIARY, CommonConfig.SHARE_TO_REPORT_DIARY, CommonConfig.SHARE_TO_DELETE_DIARY};
        int len = ids1.length;
        if (!withDiaryDelete) {
            len = ids1.length - 1;
        }
        for (int i = 0; i < len; i++) {
            ItemShareObject shareObject = new ItemShareObject();
            shareObject.setImageID(ids1[i]);
            shareObject.setShareContent(contents1[i]);
            shareObject.setShareType(shareTypes1[i]);
            shareList.add(shareObject);
        }
        return shareList;
    }

    /**
     * 更新底部view
     *
     * @param view
     * @param object
     */
    private void updateViewBar(View view, ItemDiaryDetailObject object) {
        EditText et_comment_icon = view.findViewById(R.id.et_comment);
        ImageView iv_like = view.findViewById(R.id.iv_like);
        ConstraintLayout iv_like_con = view.findViewById(R.id.iv_like_con);
        ImageView iv_send = view.findViewById(R.id.iv_send);
        TextView tv_like_num = view.findViewById(R.id.tv_like_num);
        tv_like_num.setText(object.getLikeCount() + "");
        //設置edittex不允許編輯
//        et_comment.setFocusable(false);
//        et_comment.setFocusableInTouchMode(false);
        iv_like.setSelected(object.getIsLiked() == 1);

        /**
         * 彈出留言View
         */
        et_comment_icon.setOnClickListener(v -> {
            type = 0;
            feedbackID = "";
            toUserID = object.getUserID();
            showCommentPopupView(v, type, feedbackID, toUserID, getResources().getString(R.string.diary_comment));
        });

        /**
         * 點讚或取消點讚事件監聽
         */
        iv_like_con.setOnClickListener(v -> {
            //不能自己點讚自己，跳轉點讚列表
            if (Cfg.UserID.equals(object.getUserID())) {
                Bundle bundle = new Bundle();
                bundle.putString(CommonConfig.DIARY_ID, object.getDiaryID());
                bundle.putInt(CommonConfig.LIKE_COUNT, object.getLikeCount());
                openActivity(ItemDiaryLikeListActivity.class, bundle);
                return;
            }

            new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                @Override
                public void Success() {
                    if (object.getIsLiked() == 1) {
                        object.setIsLiked(0);
                        object.setLikeCount(object.getLikeCount() - 1);
                    } else {
                        object.setIsLiked(1);
                        object.setLikeCount(object.getLikeCount() + 1);
                    }
                    tv_like_num.setText(object.getLikeCount() + "");
                    iv_like.setSelected(object.getIsLiked() == 1);
                    MessageEvent event = new MessageEvent();
                    event.setEvent(CommonConfig.EVENT_REFRESH_DIARY_LIST);
                    EventBus.getDefault().post(event);
                }

                @Override
                public void Fail(String error) {

                }
            }).diaryLike(this, object.getDiaryID(), object.getIsLiked());
        });

        /**
         * 傳送日記專頁
         */
        iv_send.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putInt(CommonConfig.TYPE, CommonConfig.TYPE_SEND_DIARY);
            bundle.putString(CommonConfig.MESSAGE_ID, object.getDiaryID());
            openActivity(ItemMessageSendActivity.class, bundle);
        });
    }

    /**
     * 更新流式佈局
     *
     * @param flowLayout
     * @param tags
     */
    private void updateFlowView(FlowLayout flowLayout, List<ItemDiaryTagObject> tags) {
        flowLayout.removeAllViews();

        if (tags == null)
            return;

        /**
         * 添加佈局參數
         */
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DensityUtils.dip2px(this, 20));
        params.rightMargin = DensityUtils.dip2px(this, 8);
        params.bottomMargin = DensityUtils.dip2px(this, 3);
        for (int i = 0; i < tags.size(); i++) {
            flowLayout.addView(updateFlowRowView(tags.get(i)), params);
        }
    }

    /**
     * 添加item佈局
     */
    private View updateFlowRowView(ItemDiaryTagObject object) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_tag_flow_row, null);
        TextView tv_text = view.findViewById(R.id.tv_text);
        tv_text.setText(object.getContent());
        return view;
    }

    /**
     * 添加回復評論view
     *
     * @param ll_reply_view
     * @param replyObjectList
     */
    private void updateCommentReplyView(LinearLayout ll_reply_view, List<ItemDiaryCommentReplyObject> replyObjectList, String feedbackID) {
        ll_reply_view.removeAllViews();

        if (replyObjectList == null)
            return;

        /**
         * 添加回復評論item
         */
        for (int i = 0; i < replyObjectList.size(); i++) {
            ll_reply_view.addView(updateCommentReplyRowView(replyObjectList.get(i), feedbackID));
        }
    }

    /**
     * 添加item佈局
     *
     * @return
     */
    private View updateCommentReplyRowView(ItemDiaryCommentReplyObject object, String commentID) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_diary_comment_reply_row, null);
        TextView tv_reply = view.findViewById(R.id.tv_reply);
        String replyStr;
        if (object.getToNickname().isEmpty()) {
            //回復層主
            replyStr = "<font color='#95cf63'>" + object.getFromNickname() + "</font>" + "：" + CommonUtils.getDecodeText(object.getMessage());
        } else {
            //回復用戶
            replyStr = "<font color='#95cf63'>" + object.getFromNickname() + "</font>" + " " + getResources().getString(R.string.diary_reply) + " " +
                    "<font color='#95cf63'>" + object.getToNickname() + "</font>" + "：" + CommonUtils.getDecodeText(object.getMessage());
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            tv_reply.setText(Html.fromHtml(replyStr, Html.FROM_HTML_MODE_COMPACT));
        } else {
            tv_reply.setText(Html.fromHtml(replyStr));
        }

        view.setOnClickListener(v -> {
            //判斷不能回復自己的留言
            if (object.getFromUserID().equals(Cfg.UserID)) {
                ToastShow.displayToast(ItemDiaryDetailActivity.this, getResources().getString(R.string.diary_comment_tips));
                return;
            }
            type = 1;
            feedbackID = commentID;
            toUserID = object.getFromUserID();
            showCommentPopupView(view, type, feedbackID, toUserID,
                    String.format(getResources().getString(R.string.diary_reply_hint), object.getFromNickname()));
        });

        return view;
    }

    /**
     * 显示评论弹出框
     *
     * @param view
     * @param type      判断是日记留言 还是回复用户留言
     * @param commentID 回复用户留言ID
     * @param toUserID  回复目标用户ID
     * @param hint      输入框提示
     */
    private void showCommentPopupView(View view, int type, String commentID, String toUserID, String hint) {
        this.type = type;
        this.feedbackID = commentID;
        this.toUserID = toUserID;
        view_background.setVisibility(View.VISIBLE);
        commentPopupWindow.setCommentHint(hint);
        commentPopupWindow.showSoftKeyBoard();
        commentPopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    /**
     * 获取日记详情数据
     */
    private void getDiaryDetailData() {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("DiaryID", diaryID);
        params.put("p", 1);
        params.put("pp", 500);
        client.get(Cfg.BaseUrl + "/Diary/DiaryDetail", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        commentObjectList.clear();
                        try {
                            JSONObject jsonObject = new JSONObject(response.trim()).getJSONObject("Result");
                            detailObject = new Gson().fromJson(jsonObject.toString(), ItemDiaryDetailObject.class);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        /**
                         * 显示数据
                         */
                        if (null != detailObject) {
                            txt_title.setText(detailObject.getNickname());

                            //顯示點讚信息view
                            updateViewBar(view_bar, detailObject);

                            //添加头部view信息
                            commentObjectList.add(new ItemDiaryCommentObject());
                            if (!detailObject.getFeedback().isEmpty()) {
                                commentObjectList.addAll(commentObjectList.size(), detailObject.getFeedback());
                            }
                            recycleAdapter.notifyDataSetChanged();
                        }

                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }
}
